import { login, getUserInfo, getUserDetailById } from '@/api/user.js'
import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth.js'
import { Message } from 'element-ui'
import router from '@/router/index.js'
const state = {
  token: getToken() || null,
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    state.token = data
    setToken(state.token)
    setTimeStamp()
  },

  getUserInfo(state, data) {
    state.userInfo = data
  },
  logout(state) {
    state.token = null
    state.userInfo = {}
    removeToken()
    router.push('/login')
  }
}
const actions = {
  // 获得token
  async login(store, fromData) {
    try {
      const data = await login(fromData)
      store.commit('setToken', data)
      Message.success('登录成功')

      router.push('/')
    } catch (error) {
      console.log(error)
    }
  },
  // 退出
  logout(store) {
    store.commit('logout')
  },
  // 获得用户信息
  async getUserInfo(store) {
    try {
      const data = await getUserInfo()
      const baseInfo = await getUserDetailById(data.userId)
      const baseResult = { ...data, ...baseInfo }
      store.commit('getUserInfo', baseResult)
      return baseResult
    } catch (error) {
      console.log(error)
    }
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

